<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="ftype">
        <el-select v-model="queryParams.ftype" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.kettle_database_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kettle:datasource:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kettle:datasource:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kettle:datasource:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kettle:datasource:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="border" max-height="550px" v-loading="loading" :data="datasourceList"
              @selection-change="handleSelectionChange" @row-click="rowClick"
              @sort-change="handleSortChange" :row-style="tableRowStyle" ref="datasource">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-hasPermi="['kettle:datasource:query']"
        label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row,false)"
            v-hasPermi="['kettle:datasource:query']"
          >详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="用户名" align="center" prop="username" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="密码" align="center" prop="password" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="IP地址" align="center" prop="dbhost" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="数据库名称" align="center" prop="dbname" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="端口号" align="center" prop="dbport" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="地址" align="center" prop="url" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="驱动" align="center" prop="driverClassName" width="150" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
     <el-table-column label="类型" align="center" prop="ftype">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.kettle_database_type" :value="scope.row.ftype"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" width="150" prop="createBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="编辑时间" align="center" prop="updateTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑人" align="center" width="150" prop="updateBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改ETL数据源信息对话框 -->
    <el-dialog  :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="ftype">
              <el-select @change="changeType($event)" clearable style="width: 100%"  v-model="form.ftype" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.kettle_database_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="用户名" prop="username">
              <el-input clearable v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="密码" prop="password">
              <el-input clearable v-model="form.password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="IP地址" prop="dbhost">
              <el-input clearable @blur="blurType($event)" v-model="form.dbhost" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="端口号" prop="dbport">
              <el-input clearable @blur="blurType($event)" v-model="form.dbport" placeholder="请输入端口号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="数据库名称" prop="dbname">
              <el-input clearable @blur="blurType($event)" v-model="form.dbname" placeholder="请输入数据库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.ftype != 'FILE' ? '地址' : '路径'" prop="url">
              <el-input clearable v-model="form.url" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.ftype != 'FILE'" label="驱动" prop="driverClassName">
              <el-input clearable v-model="form.driverClassName" placeholder="请输入驱动" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input clearable v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input maxlength="500"  v-model="form.remark" type="textarea"
                        placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.ftype != 'FILE'" type="success" @click="testConnection">测 试</el-button>
        <el-button type="primary" v-if="isUpdate" :loading="butloading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDatasource, getDatasource, delDatasource, addDatasource, updateDatasource ,testConnection} from "@/api/kettle/datasource";
  import { getTableRowStyle } from "@/utils/yss";
  export default {
    name: "Datasource",
    dicts: ['sys_common_status', 'kettle_database_type','database_driver','database_url'],
    data() {
      return {
        butloading:false,
        isUpdate: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // ETL数据源信息表格数据
        datasourceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        url:"",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          dbhost: null,
          dbname: null,
          name: null,
          ftype: null,
          status: null,
          remark: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          username: [
            { required: true, message: "用户名不能为空", trigger: "blur" }
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" }
          ],
          dbhost: [
            { required: true, message: "IP地址不能为空", trigger: "change" }
          ],
          dbname: [
            { required: true, message: "数据库名称不能为空", trigger: "change" }
          ],
          dbport: [
            { required: true, message: "端口号不能为空", trigger: "change" }
          ],
          url: [
            { required: true, message: "地址不能为空", trigger: "change" }
          ],
          driverClassName: [
            { required: true, message: "驱动不能为空", trigger: "change" }
          ],
          name: [
            { required: true, message: "名称不能为空", trigger: "change" }
          ],
          ftype: [
            { required: true, message: "类型不能为空", trigger: "change" }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询ETL数据源信息列表 */
      getList() {
        this.loading = true;
        listDatasource(this.queryParams).then(response => {
          this.datasourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          username: null,
          password: null,
          dbhost: null,
          dbname: null,
          dbport: null,
          url: null,
          driverClassName: null,
          name: null,
          ftype: null,
          status: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },
      changeType(value){
        for(let i in this.dict.type.database_driver){
          if(value== this.dict.type.database_driver[i].value){
            this.form.driverClassName=this.dict.type.database_driver[i].label;
           break;
          }
        }
        for(let i in this.dict.type.database_url){
          if(value== this.dict.type.database_url[i].value){
            this.url=this.dict.type.database_url[i].label;
            break;
          }
        }
        this.form.url=this.url;
        if(this.form.dbhost){
          this.form.url += this.form.dbhost
        }
        if(this.form.dbport){
          this.form.url += ":"+this.form.dbport
        }
        if(this.form.dbname){
          this.form.url+= "/"+this.form.dbname
        }
      },
      blurType(value){
        this.form.url=this.url;
        if(this.form.dbhost){
          this.form.url += this.form.dbhost
        }
        if(this.form.dbport){
          this.form.url += ":"+this.form.dbport
        }
        if(this.form.dbname){
          this.form.url+= "/"+this.form.dbname
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加数据源信息";
        this.isUpdate =true;
        this.form.ftype = this.dict.type.kettle_database_type[0].value;
        this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
      },
      /** 修改按钮操作 */
      handleUpdate(row,isUpdate) {
        this.reset();
        const id = row.id || this.ids
        getDatasource(id).then(response => {
          this.form = response.data;
        this.open = true;
        this.title = "修改数据源信息";
        this.isUpdate =true;
        if(isUpdate == false){
          this.title = "数据源信息详情";
          this.isUpdate =false;
        }
      });
      },
      testConnection(){ //测试连接
        this.$refs["form"].validate(valid => {
          if (valid) {
           testConnection(this.form).then(response => {
             this.$modal.msgSuccess(response.msg);
            });
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.butloading=true;
            if (this.form.id != null) {
              updateDatasource(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            } else {
              addDatasource(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除数据项？').then(function() {
          return delDatasource(ids);
        }).then(() => {
          this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('kettle/datasource/export', {
          ...this.queryParams
      }, `datasource_${new Date().getTime()}.xlsx`)
      },
      tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
      },
      /** 单击选中行数据 */
      rowClick(row) {
        this.$refs.datasource.toggleRowSelection(row);
      }
    }
  };
</script>
